package com.hkj.configcenter.core.utils;

import com.alibaba.fastjson.JSON;
import com.hkj.configcenter.core.Context;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;

@Slf4j
public class FieldUtils {

    /**
     * 设置 instance 对应的 Field值
     */
    public static void set(Object instance, Field field, String value) {
        try {
            Object data = transform(field.getType(), value);
            field.set(instance, data);
            log.info("【配置中心】参数写入成功{}.{}={}", instance.getClass().getName(), field.getName(), data);
        } catch (Throwable e) {
            throw new IllegalArgumentException(String.format("字段设置有误 fieldName = %s, value = %s", field.getName(), value));
        }
    }

    /**
     * 将value 转换为 type类型的数据
     */
    public static Object transform(Class<?> type, String value) {
        if (type == String.class) {
            return value;
        } else if (type == int.class || type == Integer.class) {
            return Integer.parseInt(value);
        } else if (type == boolean.class || type == Boolean.class) {
            if ("1".equals(value) || "true".equals(value)) {
                return true;
            }
            return false;
        } else if (type == double.class || type == Double.class) {
            return Double.parseDouble(value);
        } else if (type == long.class || type == Long.class) {
            return Long.parseLong(value);
        } else if (type == short.class || type == Short.class) {
            return Short.parseShort(value);
        } else if (type == byte.class || type == Byte.class) {
            return Byte.parseByte(value);
        } else if (type == float.class || type == Float.class) {
            return Float.parseFloat(value);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(value);
        }
        return JSON.parseObject(value, type);
    }

    public static String getUnremarkValue(String value) {
        value = value.replaceAll("[\\n\\r]", "").trim();
        if (value.indexOf(Context.SPLIT_FLAG) > 0) {
            return value.substring(0, value.indexOf(Context.SPLIT_FLAG));
        }
        return value;
    }

    public static String getRemarkValue(String value) {
        if (value.indexOf(Context.SPLIT_FLAG) > 0) {
            return value.substring(value.indexOf(Context.SPLIT_FLAG) + 2, value.length());
        }
        return "";
    }

    public static byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int i = 0;
        while ((i = inputStream.read(b)) != -1) {
            bos.write(b, 0, i);
        }
        return bos.toByteArray();
    }

}
